package com.wy2.eclipse.tool.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wy2.core.tool.DatetimeTools;
import com.wy2.core.tool.IoTools;
import com.wy2.eclipse.tool.lib.TemplateConfigManager;
import com.wy2.eclipse.tool.lib.common.Constants;
import com.wy2.eclipse.tool.lib.common.IDEUtils;
import com.wy2.eclipse.tool.lib.git.CloneRepositoryRun;
import com.wy2.eclipse.tool.lib.git.GitClient;
import com.wy2.eclipse.tool.lib.git.GitJob;
import com.wy2.eclipse.tool.lib.git.GitRun;
import com.wy2.eclipse.tool.lib.git.PullRun;
import com.wy2.eclipse.tool.lib.neoodb.SessionManager;
import com.wy2.eclipse.tool.ui.preferences.PreferenceConstants;

/**
 * The activator class controls the plug-in life cycle
 */
public class UIActivator extends AbstractUIPlugin {
	private static final Logger logger = LoggerFactory.getLogger(UIActivator.class);

	// The plug-in ID
	public static final String PLUGIN_ID = "com.wy2.eclipse.tool.ui"; //$NON-NLS-1$

	public static final String LOG_PLUGIN_ID = "com.wy2.eclipse.tool.logger";

	// The shared instance
	private static UIActivator plugin;
	
	private PreferenceStore preferenceStore;
	
	private TemplateConfigManager templateConfigManager=null;

	/**
	 * The constructor
	 */
	public UIActivator() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.
	 * BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;

		// LogActivator.getDefault();
		// startLog();

		//logger.info("com.wy2.eclipse.tool.ui start.....................................");
		//logger.info("{} - {}", "com.wy2.eclipse.tool.ui", DatetimeTools.getCurrentDatetime());
		
		//IPreferenceStore iPreferenceStore =Activator.getDefault().getPreferenceStore();	
		
//		iPreferenceStore.setValue("plugin.name", "wy2-tool-suite3");
//		if(iPreferenceStore.needsSaving()) {
//			savePreferenceStore();
//		}
		logger.info("plugin.name: {}  ,plugin.version: v{} ", getBundle().getSymbolicName(), getBundle().getVersion());
		
		GitClient tempGitClient = getGitClient();
		List<GitRun> gitRuns=new ArrayList<>();
		if(tempGitClient.localRepositoryExist()) {
            gitRuns.add(new PullRun());

		}else {
            gitRuns.add(new CloneRepositoryRun());
		}
		
		
		GitJob gitJob=new GitJob("初始化数据", tempGitClient, gitRuns);
		gitJob.addJobChangeListener(new JobChangeAdapter() {
		    @Override
		    public void done(IJobChangeEvent event) {
		      final IStatus result = event.getResult();
              final GitJob job=(GitJob) event.getJob();
              if(result.isOK()) {
                  logger.info("{} 成功",job.getName());  
                  SessionManager.initSessionFactory(getDbDirectory());
                  
              }else {
                  // if(IStatus.WARNING==result.getSeverity())
                  logger.warn(job.getName()+"异常",result.getException());
                  SessionManager.initSessionFactory(getDbDirectory());
              }
              
		    }
		});
		gitJob.schedule();
		
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		
		
		logger.info("eclipse关闭时间: {} ", DatetimeTools.getCurrentDatetime());
		super.stop(context);
	}

	

	@Override
	public IPreferenceStore getPreferenceStore() {
		// Create the preference store lazily.
		if (preferenceStore == null) {
			// InstanceScope.INSTANCE added in 3.7
			//preferenceStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, PLUGIN_ID);
			String storePath=IDEUtils.getPreferenceStorePath(getBundle().getSymbolicName()+Constants.CONFIG_PREFERENCE_STORE_SUFFIX);
			preferenceStore=new PreferenceStore(storePath);
			initializeDefaultPreferences(preferenceStore);
			//initializeDefaultPluginPreferences();
			try {
				if(IoTools.isExists(storePath)) {
					preferenceStore.load();
				}				
			} catch (IOException e) {
				logger.error("首选项加载异常", e);
			}
		}
		return preferenceStore;
	}

	@Override
	protected void initializeDefaultPreferences(IPreferenceStore store) {
		//store.setDefault("plugin.name", "wy2-tool-suite");
		
		store.setDefault(PreferenceConstants.P_GIT_URL, "https://gitee.com/nnsword/wts-data.git");
		store.setDefault(PreferenceConstants.P_PROJECT_DEFAULT_GROUPID, "com.wy2");
		store.setDefault(PreferenceConstants.P_PROJECT_DEFAULT_VERSION, "1.0.0");
        //store.setDefault(PreferenceConstants.P_GIT_USER, "");
        //store.setDefault(PreferenceConstants.P_GIT_PASSWOR, "");
		super.initializeDefaultPreferences(store);
		
	}
	/** 
	 * @deprecated 
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPluginPreferences()
	 */
	@Override
	protected void initializeDefaultPluginPreferences() {
	    // TODO Auto-generated method stub
	    //super.initializeDefaultPluginPreferences();
	    initializeDefaultPreferences(getPreferenceStore());
	}
	
	@Override
	protected void savePreferenceStore() {
		//super.savePreferenceStore();
		if (preferenceStore != null) {
			try {
				this.preferenceStore.save();
			} catch (IOException e) {
				logger.error("首选项保存异常", e);
			}
		}
	}
	
	/**
	 * 数据目录
	 * @return
	 */
	public File getDataDirectory() {
	    return new File(IDEUtils.getConfigPath(),"data");
	}
	
	public File getDbDirectory() {
        File file= new File(getDataDirectory(),"dbdata");
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return file;
    }
	
	/**
	 * 模板目录
	 * @return
	 */
	public File getTemplateRootDirectory() {
        File file= new File(getDataDirectory(),"template");
        return file;
    }
	/**
	 * 得到模板配置管理器
	 * @return
	 */
	public TemplateConfigManager getTemplateConfigManager() {
	    if(templateConfigManager==null) {
	        templateConfigManager=new TemplateConfigManager(getTemplateRootDirectory());
	    }
	    return this.templateConfigManager;
	}
	
	private GitClient gitClient=null;
	public GitClient getGitClient() {
	    if(gitClient==null) {
	        File localDirectory = getDataDirectory();
	        String remotePath= getPreferenceStore().getString(PreferenceConstants.P_GIT_URL); //"https://gitee.com/nnsword/wts-data.git";
	        gitClient=new GitClient(localDirectory, remotePath);
	        try {
                gitClient.init();
                //logger.info("git 初始化成功......");
            } catch (IOException e) {
                logger.error("git 初始化异常", e);
            }
	    }
	    return gitClient;
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static UIActivator getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given plug-in relative
	 * path
	 *
	 * @param path
	 *            the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}
}
